// pages/shopping/orderConfirm/orderConfirm.js
var app = getApp();
var appointment_time_id='';
var scene_id='';
var cooker_id="";
var ch_latitude = "";
var ch_longitude = "";
var canDo=true;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goods_list: [],//商品列表
    goods_index: '',
    contacts:'',
    contact_number:'',
    cusDetail:'',//
    to_door: '',//上门日期
    start_time: '',//开始选择时间
    end_time: '',
    time_list: '',//上门时间
    time_index:'',//上门索引
    typeList: [],//合同类型列表
    type_index: '',//选择的合同类型下标
    server_list:[],//服务场景
    server_index:'',//
    cooker_list:[],//炉具类型
    cooker_index: '',//
    valueName: [], //设置回显选择的地址(name)
    getAreaMsg: '', //选择的地址信息
    add_ress:'',//详细地址
    fanArr: [{ power: '', focal_eye: '', focal_eye_name: '', index: ''}],
    focal_eye_list: [],//灶眼类型
    cookerArr: [{ cooker_type: '', cooker_type_name: '', num: 1, water_quantity: '', gas_consumption: '', second: '', index: '' }],//测量信息
    other_cooker_num: '',//其他炉具数量
    imgUrl: [],//显示用的
    img_url: [],//传给服务器用的
    addressShow:false,//是否打开地图
    chooseType: 1,//上传类型，1图片，2视频
    videoUrl: '',//显示用的
    video_url: '',//传给服务器用的

    // 编辑
    order_id: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

    var that=this;
    that.headid = this.selectComponent("#addressid"); //引入地址
    // that.getRangeTime();//上门日期限制
    that.getContractTypeList();//获取合同类型
    that.appointmentConfiguration();//服务场景
    that.getSearchConfig();//灶眼
    that.getStoveConfig();//炉具类型
    if (options.is_edit) { //编辑
      that.setData({
        order_id: options.order_id
      })
      that.getOrderDetail();
    } else {
      var areaId = wx.getStorageSync('area_id') || '';
      var areaName = wx.getStorageSync('areaInfo_name') || '';
      let [province_code, city_code, area_code] = areaId;
      let [province, city, area] = areaName;
      that.setData({
        getAreaMsg: areaId == '' ? '' : { areaId, areaName },
        addressShow: false
      })
      if (areaId) {
        that.getGoodsList(province_code, city_code, area_code);//获取商品列表
      }
    }
  },
  /*** 生命周期函数--监听页面显示*/
  onShow: function () {
    canDo = true;
  },
  /*** 生命周期函数--监听页面卸载 重置全局变量我也不知道为什么要用全局变量*/
  onUnload: function () {
    appointment_time_id = '';
    scene_id = '';
    cooker_id = "";
    ch_latitude = "";
    ch_longitude = "";
  },

  // 获取订单详情
  getOrderDetail() {
    var that = this;
    var order_id = that.data.order_id;
    app.ajax({
      url: 'User/Work/workOrderDetail',
      method: "POST",
      data: { work_order_id: order_id, client: 5 },
      success: function (res) {
        wx.hideLoading();
        if (res.data.code == 1000) {
          var mydata = res.data.data;

          ch_latitude = mydata.lat;
          ch_longitude = mydata.lng;
          scene_id = mydata.cooker_information.scene_type_id;

          // var time_id = mydata.appointment_time_id;
          // appointment_time_id = time_id; //预约的时间段id
          // var time_index = ''; //预约的时间段
          // that.data.time_list.forEach((item, index) => {
          //   if (time_id == item.time_id) {
          //     time_index = index;
          //   }
          // })

          var type_index =  ''; //合同类型
          that.data.typeList.forEach((item, index) => {
            if (item.id == mydata.type) {
              type_index = index;
            }
          })

          var server_index = ''; //服务场景
          that.data.server_list.forEach((item, index) => {
            if (mydata.cooker_information.scene_type_id == item.id) {
              server_index = index;
            }
          })

          let areaId = [mydata.province_code, mydata.city_code, mydata.area_code];
          let areaName = [mydata.province, mydata.city, mydata.area];
          if (areaId) {
            that.getGoodsList(mydata.province_code, mydata.city_code, mydata.area_code);//获取商品列表
          }

          that.setData({
            orderDetail: mydata,
            contacts: mydata.contacts,
            contact_number: mydata.contact_number,
            equipments_id: mydata.equipments_id,
            // to_door: mydata.appointment_time[0],//上门日期
            // time_index: time_index,
            type_index: type_index,
            server_index: server_index,
            getAreaMsg: areaId == '' ? '' : { areaId, areaName },
            addressShow: false,
            add_ress: mydata.service_address,
            fanArr: mydata.cooker_information.draught_fan,
            cookerArr: mydata.cooker_information.cooker_type,
            other_cooker_num: mydata.cooker_information.other_cooker_num,
            cooker_brand: mydata.cooker_information.cooker_brand,
            cooker_model_number: mydata.cooker_information.cooker_model_number,
            cooker_num: mydata.cooker_information.cooker_num,
            expected_renovation_num: mydata.cooker_information.expected_renovation_num,
            buy_date: mydata.cooker_information.cooker_purchase_time,
            gas_fee: mydata.cooker_information.gas_fee,
            imgUrl: mydata.img,
            img_url: mydata.cooker_information.img,
            videoUrl: mydata.cooker_information.video,
            video_url: mydata.cooker_information.video_url,
            user_remarks: mydata.cooker_information.user_remarks,
          })
        }
      }
    })
  },
  //获取时间段以及限制
  getRangeTime() {
    var that = this;
    app.ajax({
      url: 'Common/Common/getRangeTime',
      method: "POST",
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            time_list: res.data.data.time,
            start_time: res.data.data.date.start,
            end_time: res.data.data.date.end,
          })
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //获取合同类型
  getContractTypeList() {
    var that = this;
    app.ajax({
      url: 'Common/Common/getSearchConfig',
      method: "POST",
      data: { config_name: 'contract_type' },
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            typeList: res.data.data
          })
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //系统配置下拉选项
  appointmentConfiguration() {
    var that = this;
    app.ajax({
      url: 'Common/Common/appointmentConfiguration',
      method: "POST",
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            server_list: res.data.data.scene_type,
          })
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //获取炉具类型下拉选项
  getStoveConfig() {
    var that = this;
    app.ajax({
      url: 'Common/Common/getStoveConfig',
      method: "POST",
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            cooker_list: res.data.data
          })
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //获取商品列表
  getGoodsList: function (provice_code, city_code, area_code) {
    var that = this;
    app.ajax({
      url: 'User/Equipment/index',
      method: "POST",
      data: {
        provice_code: provice_code,
        city_code: city_code,
        area_code: area_code,
        page: 1,
        pageSize: 9999
      },
      success: function (res) {
        if (res.data.code == 1000) {
          var goods = res.data.data.data;
          var goods_index = '';
          if (that.data.orderDetail){
            goods.forEach((item, index) => {
              if (that.data.orderDetail.equipments_id == item.equipments_id) {
                goods_index = index;
              }
            })
          }
          that.setData({
            goods_list: goods,
            goods_index: goods_index,
          })
        }
      }
    })
  },
  //选择产品前先选择地址
  bindGoods(){
    if (!this.data.getAreaMsg) {
      app.showToast('请先选择改造地址');
      return
    }
  },
  //选择产品
  bindGoodsChange(e){
    this.setData({
      goods_index: e.detail.value,
    })
  },
  //选择合同类型
  bindTypePicker(e) {
    this.setData({
      type_index: e.detail.value,
    })
  },
  //灶眼配置下拉选项
  getSearchConfig() {
    var that = this;
    app.ajax({
      url: 'Common/Common/getSearchConfig',
      method: "POST",
      data: {config_name:"a_few_eyes"},
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            focal_eye_list: res.data.data,
          })
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },

  //服务场景
  bindServerPicker(e) {
    var that = this;
    this.setData({
      server_index: e.detail.value
    })
    scene_id = that.data.server_list[e.detail.value].id
  },
  //炉具类型
  bindCookerPicker(e) {
    let { index } = e.currentTarget.dataset;
    let cookerArr = this.data.cookerArr;
    cookerArr[index].index = e.detail.value;
    cookerArr[index].cooker_type = this.data.cooker_list[index].id;
    cookerArr[index].cooker_type_name = this.data.cooker_list[index].name;
    cookerArr[index].water_quantity = this.data.cooker_list[index].water_quantity;
    this.setData({ cookerArr });
  },
  //灶眼选择
  bindFocalEyePicker(e) {
    let { index } = e.currentTarget.dataset;
    let fanArr = this.data.fanArr;
    fanArr[index].index = e.detail.value;
    fanArr[index].focal_eye = this.data.focal_eye_list[index].id;
    fanArr[index].focal_eye_name = this.data.focal_eye_list[index].name;
    this.setData({ fanArr });
  },
  //上门日期
  startDateChange: function (e) {
    this.setData({
      to_door: e.detail.value
    })
  },
  //选择时间段
  bindPickerChange: function (e) {
    let that = this;
    let time_index = e.detail.value;
    var time_list = that.data.time_list;
    var t_id = time_list[time_index].time_id;
    that.setData({
      time_index: time_index
    })
    appointment_time_id = t_id;
  },
  //选择地址
  openAeraFun() {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        console.info(res);
        that.setData({
          add_ress: res.name
        })
        ch_latitude= res.latitude;
        ch_longitude=res.longitude;
      },
    })
  },
  //打开地图选择
  openAddress() {
    var that = this;
    this.headid.startAddressAnimation(true);
    this.setData({
      addressShow:true
    })
  },
  //确定接受
  getSure(data) {
    var that = this;
    let [province_code, city_code, area_code] = data.detail.areaId;
    let [province, city, area] = data.detail.areaName;
    that.setData({
      getAreaMsg: data.detail,
      addressShow:false,
      goods_list: [],
      goods_index: '',
    })
    that.getGoodsList(province_code, city_code, area_code);//获取商品列表
  },
  cancel_fun(){
    this.setData({
      addressShow: false
    })
  },
  //添加风机功率
  addFanBtn(){
    var fanArr = this.data.fanArr;
    if (fanArr.length>99){
      return false;
    }
    var obj = { power: '', focal_eye: '', focal_eye_name: '', index: '' };
    fanArr.push(obj);
    this.setData({ fanArr})
  },
  //删除风机功率
  cutFanBtn(e){
    let { index } = e.currentTarget.dataset;
    let fanArr = this.data.fanArr;
    fanArr.splice(index, 1);
    this.setData({ fanArr })
  },
  //添加炉具
  addCookerBtn() {
    var cookerArr = this.data.cookerArr;
    if (cookerArr.length > 99) {
      return false;
    }
    var obj = { cooker_type: '', cooker_type_name: '', num: 1, water_quantity: '', gas_consumption: '', second: '', index: '' };
    cookerArr.push(obj);
    this.setData({ cookerArr })
  },
  //删除炉具
  cutCookerBtn(e) {
    let { index } = e.currentTarget.dataset;
    let cookerArr = this.data.cookerArr;
    cookerArr.splice(index, 1);
    this.setData({ cookerArr })
  },
  //输入联系人
  inputContacts(e){
    this.setData({ contacts:e.detail.value })
  },
  //输入联系电话
  inputTelphone(e) {
    this.setData({ contact_number: e.detail.value })
  },
  //监听输入
  inputFan(e){
    let { index } = e.currentTarget.dataset;
    let fanArr = this.data.fanArr;
    fanArr[index].power = e.detail.value;
    this.setData({ fanArr })
  },
  //监听炉具水量输入
  inputCooker1(e) {
    let { index } = e.currentTarget.dataset;
    let cookerArr = this.data.cookerArr;
    cookerArr[index].water_quantity = e.detail.value;
    this.setData({ cookerArr })
  },
  //监听炉具燃气输入
  inputCooker2(e) {
    let { index } = e.currentTarget.dataset;
    let cookerArr = this.data.cookerArr;
    cookerArr[index].gas_consumption = e.detail.value;
    this.setData({ cookerArr })
  },
  //监听炉具时间输入
  inputCooker3(e) {
    let { index } = e.currentTarget.dataset;
    let cookerArr = this.data.cookerArr;
    cookerArr[index].second = e.detail.value;
    this.setData({ cookerArr })
  },
  //监听炉具数量输入
  inputCooker4(e) {
    let { index } = e.currentTarget.dataset;
    let cookerArr = this.data.cookerArr;
    cookerArr[index].num = e.detail.value;
    this.setData({ cookerArr })
  },

  // 取消按钮
  cancelFun() {
    wx.showModal({
      title: '是否返回上一页面?',
      content: '当前数据不会保存',
      confirmColor: '#DF0101',
      success(res) {
        if (res.confirm) {
          wx.navigateBack({
            delta: 1
          })
        } else if (res.cancel) {

        }

      }
    })
  },


  // 添加图片 打开中间页
  openChoose(e) {
    var that = this;
    that.setData({
      isShow: true,
      chooseType: e.currentTarget.dataset.choose
    })
  },
  //关闭中间页(关闭)
  closeShoot() {
    var that = this;
    that.setData({
      isShow: false,
    })
  },
  //打开相机
  openAbout(e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    //关闭中间页面 打开自定义照相机
    that.setData({
      isShow: false,
    })
    var length = that.data.imgUrl.length || 0;
    var count = 9 - length;
    var sourceType = '';
    if (type == 1) {
      sourceType = 'album';
    } else if (type == 2) {
      sourceType = 'camera';
    }
    if (that.data.chooseType==1){//图片
      wx.chooseImage({
        count: count,
        sizeType: ['compressed'],
        sourceType: [sourceType],
        success: function (res) {
          const tempFilePaths = res.tempFilePaths;
          wx.showLoading({
            mask: true,
            title: '上传中',
          })
          that.uploadImageArr(tempFilePaths);
        },
      })
    }else{//视频
      wx.chooseVideo({
        sourceType: [sourceType],
        compressed: true,
        maxDuration: 60,
        camera: 'back',
        success: function (res) {
          if (res.duration>60){
            app.showToast('视频时长必须小于60秒');
            return
          }
          const tempFilePath = res.tempFilePath;
          wx.showLoading({
            mask: true,
            title: '上传中',
          })
          that.uploadImageArr([tempFilePath]);
        },
      })
    }
  },
  // 上传环境图 -多图
  uploadImageArr(tempFilePaths) {
    console.log('获取到的数据你好', tempFilePaths)
    var that = this;
    for (var i in tempFilePaths) {
      wx.uploadFile({
        url: app.globalData._url + 'Common/Common/upload',
        filePath: tempFilePaths[i],
        name: 'file',
        success: function (result) {
          if (result.statusCode !== 200) {
            wx.hideLoading();
            app.showToast('上传失败,请重新上传');
            return
          }
          var data = JSON.parse(result.data);
          if (data.code == 1000) {
            if(that.data.chooseType==1){//图片
              var imgUrl = that.data.imgUrl;
              var img_url = that.data.img_url;
              imgUrl.push(data.data.all_url);
              img_url.push(data.data.url);
              that.setData({
                imgUrl,
                img_url
              })
              wx.hideLoading();
            }else{//视频
              var videoUrl = data.data.all_url;
              var video_url = data.data.url;
              that.setData({
                videoUrl,
                video_url
              })
              wx.hideLoading();
            }
          }else{
            wx.hideLoading();
            app.showToast('上传失败,请重新上传');
          }
        },
        fail: function (fail) {
          wx.hideLoading();
          app.showToast('上传失败,请重新上传');
        }
      })
    }
  },
  // 图片放大预览
  previewImage(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.url,
      urls: this.data.imgUrl // 需要预览的图片http链接列表
    })
  },
  // 删除图片
  reduceImg(e) {
    var imgUrl = this.data.imgUrl;
    var img_url = this.data.img_url;
    var index = e.currentTarget.dataset.index;
    imgUrl.splice(index, 1);
    img_url.splice(index, 1);
    this.setData({
      imgUrl,
      img_url
    })
    // this.changeSubmit();
  },
  //删除视频
  reduceVideo(){
    this.setData({
      videoUrl: '',
      video_url: '',
    })
  },

  //提交表单
  formSubmit(e) {
    let that=this;
    let formVal = e.detail.value;
    let fanArr = that.data.fanArr;
    let [ province_code, city_code, area_code ] = that.data.getAreaMsg.areaId ? that.data.getAreaMsg.areaId:'';
    let [ province, city, area ] = that.data.getAreaMsg.areaName ? that.data.getAreaMsg.areaName:'';
    let numreg = /^[1][3-9][\d]{9}$/; //手机号码正则
    if (formVal.contacts == '') {
      app.showToast('联系人不能为空', "none", 2000, function () { });
      return false;
    }
    if (formVal.contacts == '') {
      app.showToast('联系电话不能为空', "none", 2000, function () { });
      return false;
    }
    if (numreg.test(formVal.contact_number) == false || formVal.contact_number.length<11) {
      app.showToast('请输入正确的联系电话', "none", 2000, function () { });
      return false;
    }
    // if (formVal.appointment_date == '') {
    //   app.showToast('请选择预约上门日期', "none", 2000, function () { });
    //   return false;
    // }
    // if (appointment_time_id==''){
    //   app.showToast('请选择预约上门时间', "none", 2000, function () { });
    //   return false;
    // }
    if (that.data.getAreaMsg==''){
      app.showToast('请选择省市区', "none", 2000, function () { });
      return false;
    }
    if (ch_latitude == '' || ch_longitude==''){
      app.showToast('请选择改造地址', "none", 2000, function () { });
      return false;
    }
    if (that.data.type_index === '') {
      app.showToast('请选择合同类型', "none", 2000, function () { });
      return false;
    }
    if (scene_id == '') {
      app.showToast('请选择服务场景', "none", 2000, function () { });
      return false;
    }
    let updata={
      client: 5, //1用户端5经销商端
      work_order_id: that.data.order_id,
      equipments_id: that.data.goods_list[that.data.goods_index].equipments_id,
      contacts:formVal.contacts,
      contact_number:formVal.contact_number,
      type: that.data.typeList[that.data.type_index].id || '',
      // appointment_date: formVal.appointment_date,
      // appointment_time_id: appointment_time_id,
      scene_type: scene_id,
      cooker_type: that.data.cookerArr,
      other_cooker_num: formVal.other_cooker_num,
      cooker_brand: formVal.cooker_brand,
      cooker_model_number: formVal.cooker_model_number,
      cooker_num: formVal.cooker_num,
      expected_renovation_num: formVal.expected_renovation_num,
      cooker_purchase_time: formVal.cooker_purchase_time,
      gas_fee: formVal.gas_fee,
      province,
      province_code,
      city,
      city_code,
      area,
      area_code,
      address: formVal.address,
      lat: ch_latitude,
      lng: ch_longitude,
      img: that.data.img_url,
      video: that.data.video_url,
      draught_fan: that.data.fanArr,
      user_remarks: formVal.user_remarks,
    }
    if (!canDo){
      return false
    }
    canDo=false;
    app.ajax({
      url: that.data.order_id ? 'User/Order/editOrder' : 'User/Order/addOrder',
      data: updata,
      success: function (res) {
        if (res.data.code == 1000) {
          app.showToast('报单成功');
          setTimeout(()=>{
            wx.redirectTo({
              url: '/pages/user/myOrderList/myOrderList?client=5', //1用户端5经销商端
            })
          },1000)
        } else {
          app.showToast(res.data.message, "none", 2000, function () { });
        }
        setTimeout(()=>{
          canDo = true;
        },1000)
      }
    })
  },

})
